#include "myaudioplayer.h"
#include <QDateTime>
#include <QDebug>
#include "utils/signalcenter.h"
MyAudioPlayer::MyAudioPlayer(QObject *parent)
    : QObject{parent}
    , MediaDevices(new QMediaDevices(this))
    , volume(0.5)
    , myIODevice(nullptr)
    , startplaying(false)
{
    outputDevices = MediaDevices->audioOutputs();
    for (auto &device : outputDevices) {
        QString description = device.description();
        outputDevicesDescription.emplace_back(description);
    }

    connect(&SignalCenter::instance(),
            &SignalCenter::audioVolumeChange,
            this,
            &MyAudioPlayer::onAudioVloumeChange);
}

MyAudioPlayer::~MyAudioPlayer()
{
}

void MyAudioPlayer::chooseOutputDevice(uint8_t index)
{
    selectOutputDevices = outputDevices[index];
    QAudioFormat format = selectOutputDevices.preferredFormat();
    audioSinkOutput = new QAudioSink(selectOutputDevices, format, this);
    audioSinkOutput->setVolume(volume);
    qDebug() << "chooseOutputDevice" << selectOutputDevices.description();
}

void MyAudioPlayer::onPause()
{
    audioSinkOutput->suspend();
}

void MyAudioPlayer::onResume()
{
    audioSinkOutput->resume();
}

void MyAudioPlayer::startPlay()
{
    myIODevice = new MyIODevice(this);
    myIODevice->start();
    audioSinkOutput->start(myIODevice); //开启音频播放，并绑定输入的数据源
    qDebug() << "QAudioSink::state():" << audioSinkOutput->state(); // QAudio::ActiveState
    startplaying = true;
}

void MyAudioPlayer::stopPlay()
{
    if (startplaying) {
        if (myIODevice) {
            myIODevice->stop();
        }

        if (audioSinkOutput) {
            audioSinkOutput->stop();
        }

        startplaying = false;
    }
}

void MyAudioPlayer::replay()
{
    stopPlay();
    myIODevice->start();
    audioSinkOutput->start(myIODevice);
}

QVector<QString> MyAudioPlayer::getOutputDevicesDescription()
{
    if (!outputDevicesDescription.isEmpty())
        return outputDevicesDescription;
    else {
        qDebug() << "outputDevicesDescription is empty";
        return {};
    }
}

void MyAudioPlayer::onAudioVloumeChange(float value)
{
    qDebug() << "当前音量为：" << value << QDateTime::currentDateTime().toString("hh:mm:ss.zzz");
    if (!audioSinkOutput) {
        volume = value;
        qDebug() << "80";
    } else {
        audioSinkOutput->setVolume(value);
    }
}
